package com.example.demo.api;

import cn.hankchan.redis.sdk.RedisCacheService;
import cn.hankchan.util.UniqueUtils;
import com.example.demo.model.ApiResult;
import com.example.demo.proxy.HttpRequestControlProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

/**
 * @author hankChan
 *         2018/2/6 0006.
 */
@RestController
public class HttpRequestControlAPIs {

    @Autowired
    RedisCacheService redisCacheService;

    @Autowired
    @Qualifier("httpRequestControlProxy")
    HttpRequestControlProxy httpRequestControlProxy;

    /**
     * 分布式锁，多人请求，只允许一个调用者
     */
    @RequestMapping(value = "/api/redis/lock",
            method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ApiResult allowOneHandleOnSameTime(
            @RequestParam(value = "parameters", required = false) String parameters,
            @CookieValue(name = "token_key", required = false) String tokenKey) {
        String requestId = String.valueOf(UniqueUtils.getId());
        String token = redisCacheService.getByString(tokenKey);
        // 限流调用频率粒度控制到具体的接口
        String key = token + "/api/redis/lock";
        return ApiResult.prepare().success(
                httpRequestControlProxy.allowOneHandleOnSameTime(key, parameters, requestId));
    }

    /**
     * 接口防刷，限制调用频率
     */
    @RequestMapping(value = "/api/redis/limit",
            method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ApiResult allowOneRequestPerMinutes(
            @RequestParam(value = "parameters", required = false) String parameters,
            @CookieValue(name = "token_key", required = false) String tokenKey) {
        String requestId = String.valueOf(UniqueUtils.getId());
        String token = redisCacheService.getByString(tokenKey);
        // 限流调用频率粒度控制到具体的接口
        String key = token + "/api/redis/limit";
        return ApiResult.prepare().success(
                httpRequestControlProxy.allowOneRequestPerMinutes(key, parameters, requestId));
    }
}
